import {reqGetShopCartList,reqDelCheckGood,reqcutGoodCheckedStatus} from '@/api/index'

const state={
    shopCartList:{},
    cartInfoList:[]
};
const actions={
    //获取购物车内容列表
    async getShopCartList($store){
        let result= await reqGetShopCartList();
        // console.log(result)
        if (result.data.code==200) {
            result=result.data.data[0];
            console.log(result);
            console.log("成功触发");
            $store.commit("GETSHOPCARTLIST",result);
        }
    },
    //删除选中内容
    async delCheckGood($store,skuId){
        let result=await reqDelCheckGood(skuId);
        console.log(result)
        if (result.data.code==200) {
            console.log("成功")
            return 'ok'
        }else{
            return Promise.reject([new Error("faile")]);
        }
    },
    //切换选中状态
    async cutGoodCheckedStatus($store,{skuId,isChecked}){
        let result= await reqcutGoodCheckedStatus(skuId,isChecked);
        console.log(result);
        if (result.data.code==200) {
            return 'ok'
        }else{
           return Promise.reject([new Error("faile")]);
        }
    },
    // 切换全部的选中状态
    changeAllChecked($store,isChecked){
        let promiseArr=[];
        $store.state.cartInfoList.forEach(item => {
            let promise= $store.dispatch("cutGoodCheckedStatus",{skuId:item.skuId,isChecked})
            promiseArr.push(promise);
        });
        //这个 Promise.all 是什么
        //和数组的every方法比较相似,一旦失败,便终止进程,返回错误;全部成功便返回true
        return Promise.all(promiseArr);
        // if (promiseArr.every.isChecked==isChecked) {
        //     return 'ok'
        // }else{
        //     return Promise.reject([new Error])
        // }
    }
};
const mutations={
    GETSHOPCARTLIST(state,shopCartList){
        state.shopCartList=shopCartList;
        state.cartInfoList=shopCartList.cartInfoList;
    }
};
const getters={
    
    // cartInfoList:state=>state.shopCartList.cartInfoList,
};
export default {state,actions,mutations,getters};